import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 可复用BIO socket
 */
public class BIOServer {

    public static int PORT = 6661 ;
    public static String CHARSET = "UTF-8";


    public static void main(String[] args) {

        System.out.println("started application");


        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.setReuseAddress(true);//设置端口可复用 ===> 需要在端口开启前设置改属性

            serverSocket.bind(new InetSocketAddress(PORT));

            while (true){

                Socket clientChannel = serverSocket.accept();

//                echo(clientChannel);

                //多线程接受client请求
                threadEcho(clientChannel);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void threadEcho(Socket clientChannel){

        new Thread(()->{
            try {
                echo(clientChannel);
            } catch (InterruptedException e) {

            }
        }).start();

    }

    public static void echo(Socket clientChannel) throws InterruptedException {


        System.out.println("接收到请求，等待打印");
        Thread.sleep(5000);

        InputStream inputStream;
        BufferedReader br = null;
        StringBuffer stringBuffer = new StringBuffer();

        try {
            inputStream = clientChannel.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
            String line;
            while ((line = br.readLine()) != null){

                stringBuffer.append(line);
            }
            System.out.println(stringBuffer.toString());
        } catch (IOException e) {

            e.printStackTrace();
        }finally {

            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
